package calao.client.ui;

import calao.client.util.CalendarDate;
import calao.client.util.DateRange;
import calao.client.util.DateRange.IndexRange;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;

/** Tables data over a period of time.
 */
public class TimeTable 
extends FastTable
{
	
	private final static int HEADER_HEIGHT = 18;
	
	public final static int COLUMN_WIDTH = 20;
	
	public final static String STYLE = "calao-TimeTable";
	public final static String MONTH_HEADER_STYLE = "monthHeader";
	public final static String DAY_HEADER_STYLE = "dayHeader";
	public final static String WEEK_START_STYLE = "weekStart";
	
	final DateTimeFormat monthFormat = DateTimeFormat.getFormat("MMMM");

	final DateRange dateRange;
	
	int headerRows = 0;

	public TimeTable(DateRange dateRange)
	{
		super(dateRange.getDayCount());
		this.dateRange = dateRange;
		Elements.setWidth(getElement(), dateRange.getDayCount()*COLUMN_WIDTH);
		addStyleName(STYLE);
	}

	public void buildMonthHeaders()
	{
		int index = 0;
		while (index<dateRange.getDayCount()) {
			CalendarDate month = dateRange.getDay(index);
			IndexRange range = dateRange.getMonthDays(month);
			Element header = addCell(monthFormat.format(month.getTime()), 
						range.length(), MONTH_HEADER_STYLE);
			Elements.setWidth(header, range.length()*COLUMN_WIDTH);
			index = range.getEnd() + 1;
		}
		headerRows++;
	}
	
	public void buildDayHeaders()
	{
		for (int col=0; col<dateRange.getDayCount(); col++) {
			addCell(""+dateRange.getDay(col).getDay(), 1, DAY_HEADER_STYLE);
		}
		headerRows++;
	}
	
	public void buildHeaders()
	{
		buildMonthHeaders();
		buildDayHeaders();
	}
	
	protected Element addCell(int colSpan, String style, Widget widget, String text)
	{
		int index = getColumn();
		Element cell = super.addCell(colSpan, style, widget, text);
		if (getRowCount()>2 && dateRange.isFirstDayOfWeek(index)) {
			UIObject.setStyleName(cell, WEEK_START_STYLE, true);
		}
		return cell;
	}
	
	public int getColumnLeft(int column)
	{
		return column*(COLUMN_WIDTH+1);
	}
	
	public int getContentTop()
	{
		return headerRows*HEADER_HEIGHT+1;
	}
	
	public int getColSpanWidth(int colSpan)
	{
		return colSpan*(COLUMN_WIDTH+1);
	}

}
